package org.edu.modules.jxgz.controller;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.edu.common.system.base.controller.BaseController;
import org.edu.common.api.vo.Result;
import org.edu.common.system.query.QueryGenerator;
import org.edu.modules.jxgz.api.JxrwApiService;
import org.edu.modules.jxgz.entity.SkjhCopyParam;
import org.edu.modules.jxgz.entity.VeJwSkjh;
import org.edu.modules.jxgz.entity.VeJwSkjhmx;
import org.edu.modules.jxgz.service.IVeJwSkjhService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.edu.modules.jxgz.service.IVeJwSkjhmxService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.edu.common.aspect.annotation.AutoLog;

 /**
 * @Description: ve_jw_skjh
 * @Author: jeecg-boot
 * @Date:   2021-05-26
 * @Version: V1.0
 */
@Api(tags="ve_jw_skjh")
@RestController
@RequestMapping("/jxgz/veJwSkjh")
@Slf4j
public class VeJwSkjhController extends BaseController<VeJwSkjh, IVeJwSkjhService> {
	@Autowired
	private IVeJwSkjhService veJwSkjhService;
	@Autowired
	private IVeJwSkjhmxService veJwSkjhmxService;
	@Autowired
	private JxrwApiService jxrwApiService;
	
	/**
	 * 分页列表查询
	 *
	 * @param veJwSkjh
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "ve_jw_skjh-分页列表查询")
	@ApiOperation(value="ve_jw_skjh-分页列表查询", notes="ve_jw_skjh-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(VeJwSkjh veJwSkjh,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<VeJwSkjh> queryWrapper = QueryGenerator.initQueryWrapper(veJwSkjh, req.getParameterMap());
		queryWrapper.getExpression().getOrderBy().clear();
		queryWrapper.orderByDesc("createtime");
		Page<VeJwSkjh> page = new Page<VeJwSkjh>(pageNo, pageSize);
		IPage<VeJwSkjh> pageList = veJwSkjhService.page(page, queryWrapper);



		return Result.ok(pageList);
	}
	
	/**
	 *   保存或提交
	 *
	 * @param veJwSkjh
	 * @return
	 */
	@AutoLog(value = "ve_jw_skjh-保存或提交")
	@ApiOperation(value="ve_jw_skjh-保存或提交", notes="ve_jw_skjh-保存或提交")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody VeJwSkjh veJwSkjh) {

		// 没制定过计划，则创建
		if(veJwSkjh.getId() == null){
			veJwSkjh.setTerminalid(1);
			veJwSkjh.setCreatetime(new BigDecimal(System.currentTimeMillis()/1000).intValue());
			veJwSkjhService.save(veJwSkjh);
			for(VeJwSkjhmx item : veJwSkjh.getSkjhmxList()) {
				// 授课计划ID
				item.setSkjhid(veJwSkjh.getId());
			}
		}
		// 已经制定
		else{
			VeJwSkjh temp = veJwSkjhService.getById(veJwSkjh.getId());
			if(temp.getIscomplete() == 1){
				return Result.error("已完成，无法修改授课计划");
			}
		}

		// 保存
		if(veJwSkjh.getIscomplete() == 0){
			List<VeJwSkjhmx> skjhmxeList = veJwSkjh.getSkjhmxList();
			veJwSkjhmxService.saveOrUpdateBatch(skjhmxeList);
			return Result.ok("保存成功！");
		}
		// 提交，进行验证全部是否全部填写完毕
		else {
			veJwSkjh.setCompletetime(new BigDecimal(System.currentTimeMillis()/1000).intValue());
			List<VeJwSkjhmx> skjhmxeList = veJwSkjh.getSkjhmxList();
			for(VeJwSkjhmx item : skjhmxeList){
				if(StringUtils.isEmpty(item.getContent())){
					return Result.error("请填写完所有的授课计划详情");
				}
			}
			veJwSkjhService.updateById(veJwSkjh);
			veJwSkjhmxService.saveOrUpdateBatch(skjhmxeList);
			return Result.ok("提交成功！");
		}

	}

	 /**
	  * 提交已填写的授课计划
	  * @param jxrwId
	  * @return
	  */
	@AutoLog(value = "ve_jw_skjh-提交已填写的授课计划")
	@ApiOperation(value="ve_jw_skjh-提交已填写的授课计划", notes="ve_jw_skjh-提交已填写的授课计划")
	@PutMapping("/submit/{jxrwId}")
	public Result<?> submit(@PathVariable Integer jxrwId){
		LambdaQueryWrapper<VeJwSkjh> skjhWrapper = new LambdaQueryWrapper<>();
		skjhWrapper.eq(VeJwSkjh::getJxrwid, jxrwId);
		VeJwSkjh skjh = veJwSkjhService.getOne(skjhWrapper);
		if(skjh == null){
			return Result.error("未制定授课计划");
		}

		LambdaQueryWrapper<VeJwSkjhmx> skjhmxWrapper = new LambdaQueryWrapper<>();
		skjhmxWrapper.eq(VeJwSkjhmx::getSkjhid, skjh.getId());
		// 获取授课计划详情，并验证是否全部填写完毕
		List<VeJwSkjhmx> skjhmxeList = veJwSkjhmxService.list(skjhmxWrapper);
		for(VeJwSkjhmx item : skjhmxeList){
			if(StringUtils.isEmpty(item.getContent())){
				return Result.error("请制定完授课计划之后，再提交");
			}
		}
		// 设置完成，且完成时间
		skjh.setIscomplete(1);
		skjh.setCompletetime(new BigDecimal(System.currentTimeMillis()/1000).intValue());

		return null;
	}

	 /**
	  * 获取是否制定授课计划
	  * @return
	  */
	@AutoLog(value = "ve_jw_skjh-获取是否制定授课计划")
	@ApiOperation(value="ve_jw_skjh-获取是否制定授课计划", notes="ve_jw_skjh-获取是否制定授课计划")
	@RequestMapping("/isFormulate")
	public Boolean getIsFormulate(@RequestParam("jxrwId") Integer jxrwId){
		LambdaQueryWrapper<VeJwSkjh> skjhWrapper = new LambdaQueryWrapper<>();
		skjhWrapper.eq(VeJwSkjh::getJxrwid, jxrwId);
		VeJwSkjh skjh = veJwSkjhService.getOne(skjhWrapper);
		return skjh != null;
	}

	@PostMapping("/copy")
	public Result<?> copy(@RequestBody SkjhCopyParam param){

		VeJwSkjh origin = veJwSkjhService.getByJxrwId(param.getJxrwId());
		if(origin == null){
			return Result.error("请选择已制定的授课计划进行复制");
		}

		LambdaQueryWrapper<VeJwSkjhmx> skjhmWrapper = new LambdaQueryWrapper<>();
		skjhmWrapper.eq(VeJwSkjhmx::getSkjhid, origin.getId());
		skjhmWrapper.select(VeJwSkjhmx::getXueshi, VeJwSkjhmx::getContent);
		List<VeJwSkjhmx> skjhmList = veJwSkjhmxService.list(skjhmWrapper);

		for(Integer id : param.getCopyIdList()){
			VeJwSkjh temp = veJwSkjhService.getByJxrwId(id);
			// 如果未制定授课计划
			if(temp != null){
				// 清楚旧数据
				veJwSkjhService.deleteByIdAndDetail(temp.getId());
			}
			Result<JSONObject> result = jxrwApiService.queryById(id);
			if(result.isSuccess()){
				// 教学任务信息
				JSONObject jxrw = result.getResult();

				temp = new VeJwSkjh();
				temp.setJxrwid(jxrw.getInteger("id"));
				temp.setSemid(jxrw.getInteger("semid"));
				temp.setJxbid(jxrw.getInteger("jxbid"));
				temp.setKcid(jxrw.getInteger("kcid"));
				temp.setZxs(jxrw.getInteger("zxs"));
				temp.setTeacheruserid(jxrw.getString("teacheruserid"));
				// 制定中
				temp.setIscomplete(0);
				// 终端ID
				temp.setTerminalid(1);
				// 保存授课计划
				veJwSkjhService.save(temp);

				// 拷贝授课计划详情
				for(VeJwSkjhmx skjhmxItem : skjhmList){
					skjhmxItem.setSkjhid(temp.getId());
				}
				veJwSkjhmxService.saveBatch(skjhmList);

			} else {
				continue;
			}

		}

		return Result.ok("复制成功");
	}

	/**
	 *  编辑
	 *
	 * @param veJwSkjh
	 * @return
	 */
	@AutoLog(value = "ve_jw_skjh-编辑")
	@ApiOperation(value="ve_jw_skjh-编辑", notes="ve_jw_skjh-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody VeJwSkjh veJwSkjh) {
		veJwSkjhService.updateById(veJwSkjh);
		return Result.ok("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "ve_jw_skjh-通过id删除")
	@ApiOperation(value="ve_jw_skjh-通过id删除", notes="ve_jw_skjh-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		veJwSkjhService.removeById(id);
		return Result.ok("删除成功!");
	}


	 /**
	  *   提交
	  *
	  * @param veJwSkjh
	  * @return
	  */
	 @AutoLog(value = "ve_jw_skjh-提交")
	 @ApiOperation(value="ve_jw_skjh-提交", notes="ve_jw_skjh-提交")
	 @PutMapping(value = "/handle")
	 public Result<?> handle(@RequestBody VeJwSkjh veJwSkjh) {

	 	//todo 权限判断
		 veJwSkjhService.updateById(veJwSkjhService.getById(veJwSkjh.getId()).setIscomplete(1));
		 return Result.ok("提交成功!");
	 }


	 /**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "ve_jw_skjh-批量删除")
	@ApiOperation(value="ve_jw_skjh-批量删除", notes="ve_jw_skjh-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.veJwSkjhService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "ve_jw_skjh-通过id查询")
	@ApiOperation(value="ve_jw_skjh-通过id查询", notes="ve_jw_skjh-通过id查询")
	@RequestMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) Integer id) {
		LambdaQueryWrapper<VeJwSkjh> skjhWrapper = new LambdaQueryWrapper<>();
		skjhWrapper.eq(VeJwSkjh::getJxrwid, id);
		VeJwSkjh veJwSkjh = veJwSkjhService.getOne(skjhWrapper);
		if(veJwSkjh==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(veJwSkjh);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param veJwSkjh
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, VeJwSkjh veJwSkjh) {
        return super.exportXls(request, veJwSkjh, VeJwSkjh.class, "ve_jw_skjh");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, VeJwSkjh.class);
    }

}
